
import time
#导入user-agent代理池
from user_agent import ua_list
from random import choice

import os
import re

import requests
#获取视频的名字
url = 'https://www.bilibili.com/video/BV1NL41157ph?p=1'
headers = {
    'user-agent': choice(ua_list)
}
res = requests.get(url,headers = headers)
str_data = res.text
names = re.findall('"part":"(.*?)",',str_data)
# print(names)
# print(len(names))

# 利用for循环下载所有视频
for i in range(55,len(names)):
    name = names[i].replace(' ','')
    # 每个视频的url
    url_ = f'https://www.bilibili.com/video/BV1NL41157ph?p={i+1}'
    headers = {
        'user-agent':choice(ua_list),
        "referer": 'https://www.bilibili.com/video/BV1NL41157ph?p=15'
    }
    res = requests.get(url_,headers = headers)
    str_data = res.text
    # print(str_data)
    #获取纯视频和纯音频url
    video_url = re.findall('"video":\[{"id":\d+,"baseUrl":"(.*?)",',str_data)[0]
    audio_url = re.findall('"audio":\[{"id":\d+,"baseUrl":"(.*?)",',str_data)[0]
    # print(video_url)
    # print(audio_url)
    # print(len(video_url))
    headers = {
        "user-agent":choice(ua_list),
        "referer":'https://www.bilibili.com/video/BV1NL41157ph?p=15'
    }
    #发送请求
    res1 = requests.get(video_url,headers = headers)
    res2 = requests.get(audio_url,headers = headers)

    video_data = res1.content
    audio_data = res2.content
    #保存纯音频纯视频文件
    with open(r'D:\BaiduNetdiskDownload\hello.py\django_video\video.mp4',"wb")as f:
        f.write(video_data)
    with open(r"D:\BaiduNetdiskDownload\hello.py\django_video\audio.mp3","wb")as f:
        f.write(audio_data)
    os.system(f'ffmpeg -i D:\BaiduNetdiskDownload\hello.py\django_video\\audio.mp3 -i D:\BaiduNetdiskDownload\hello.py\django_video\\video.mp4 -c copy D:\BaiduNetdiskDownload\hello.py\django_video\\{name}.mp4 -loglevel quiet')
    # 删除纯音频和纯视频文件，只能保留完整视频
    os.remove(r"D:\BaiduNetdiskDownload\hello.py\django_video\audio.mp3")
    os.remove(r"D:\BaiduNetdiskDownload\hello.py\django_video\video.mp4")
    #人为降低下载速度避免被反爬
    time.sleep(2)
    if i == 50:
        time.sleep(30)
    #每完成一个视频下载就打印提示语
    print(f"{name}下载完毕。。")